<?php

namespace shisou\tpinit\lib;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 生成excel文件
 *
 * @param array  $data
 * @param array  $header   表头
 * @param string $filename 文件名称
 *
 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
 */
class ExportExcel
{
    private $header;
    private $data;
    private $filename;

    public function __construct($header, $data, $filename = '')
    {
        $this->header   = $header;
        $this->data     = $data;
        $this->filename = $filename ?: date('Ymd', time());
    }

    public function download()
    {
        set_time_limit(0);

        $title_key = [];

        foreach ($this->data[0] as $key => $val) {
            $title_key[] = $key;
        }

        $unit = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY',
            'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ',
        ];

        $line_count = count($this->header);

        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象

        $n = 1;
        for ($i = 0; $i < $line_count; ++$i) {
            $objSheet->getColumnDimension($unit[$i])
                ->setWidth(25);
            $objSheet->setCellValue($unit[$i] . $n, $this->header[$i]);

            foreach ($this->data as $key => $val) {
                $m = $key + 2;
                $objSheet->setCellValue($unit[$i] . $m, ' ' . $val[$title_key[$i]]);
            }
        }

        header('Content-Disposition: attachment;filename="' . $this->filename . '.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

        ob_start();

        $filePath  = '/excel/' . $this->filename . '.xlsx';
        $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
        $objWriter->save(root_path() . 'public' . $filePath);
        $objWriter->save('php://output');

        ob_end_clean();

        return $filePath;
    }
}
